package cn.chengpengper.taskDispose;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/*@formatter:off*/

/**
 * ____________________
 * < 神兽护体，永无bug! >
 * --------------------
 *
 * @author catwing
 * @version v1.0.0
 * @date 2024/12/8 01:23
 * @description 多任务并行处理DEMO
 */

/*@formatter:on*/

public class SimpleBatchTask {
    public static void main(String[] args) {
        batchTask();
    }

    public static void batchTask() {
        long startTime = System.currentTimeMillis();
        List<String> taskList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            taskList.add("短信-" + i);
        }

        // 使用线程池批量处理任务
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());

        for (String task : taskList) {
            executorService.execute(() -> {
                try {
                    disposeTask(task);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("全部任务处理完毕，耗时(ms):" + (System.currentTimeMillis() - startTime));
        executorService.shutdown();
    }

    public static void disposeTask(String task) {
        System.out.println(String.format("【%s】发送成功", task));
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
